<?php
/**
 * Created by PhpStorm.
 * User: longli
 * VX: isa1589518286
 * Date: 2021/02/18
 * Time: 10:29
 * @link http://www.lmterp.cn
 */

namespace app\admin\controller\wms;

use app\admin\controller\BaseController;
use app\common\library\Tools;
use app\common\model\Warehouse;
use app\common\model\WarehouseBorrow;
use app\common\model\WarehouseStock;
use app\common\service\product\WarehouseService;

/**
 * 借用管理
 * Class WlocationController
 * @package app\admin\controller\wms
 */
class WborrowController extends BaseController
{
    protected $moduleName = 'warehouse_borrow';

    /**
     * 借用列表
     * @date 2021/02/18
     * @author longli
     */
    public function index()
    {
        if($this->request->isAjax())
        {
            $borrow = WarehouseBorrow::with(['win', 'wout', 'user'])
                ->where('out_id', $this->warehouse->warehouse_id)
                ->order('out_id, borrow_id desc');
            $this->searchModel($borrow, [
                'eq' => ['in_id', 'borrow_sn', 'user_id', 'status', 'check_status'],
                'times' => ['borrow_date', 'return_date'],
            ]);
            $limit = $this->getPageSize();
            $borrow = $borrow->paginate($limit);
            $this->assign('status_wait', WarehouseBorrow::STATUS_WAIT);
            $this->assign('status_cancel', WarehouseBorrow::STATUS_CANCEL);
            $this->assign('is_show_check', $this->user->hasPermissions('/wms/wborrow/check'));
            $this->assign("list", $borrow->getCollection());
            $this->assign("page", $borrow->render());
            return $this->fetch('lists');
        }
        $this->assign('warehouse', Warehouse::getAll());
        $this->assign('users', \app\common\model\Admin::getAll());
        $this->assign('check_status', \app\common\model\JobFlowModule::$CHECK_STATUS);
        $this->assign('status', WarehouseBorrow::$BORROW_STATUS);
        return $this->fetch('index');
    }

    /**
     * 借用单详情
     * @date 2021/02/17
     * @author longli
     */
    public function info()
    {
        $borrowId = $this->request->get('borrow_id');
        if(empty($borrowId)) $this->error('非法请求');
        if(!($borrow = WarehouseBorrow::get($borrowId))) $this->error('借用单不存在');
        $this->assign('borrow', $borrow);
        $this->assignCheck($borrowId);
        $this->assign('borrow_info', $this->renderTerp(WarehouseBorrow::class, $borrow->borrow_id, "wms/warehouse/terp/check_info"));
        return $this->fetch('info');
    }

    /**
     * 添加借用单
     * @date 2021/02/18
     * @author longli
     */
    public function add()
    {
        return $this->fetch('add');
    }

    /**
     * 保存借用单
     * @date 2021/02/18
     * @author longli
     */
    public function save()
    {
        $this->validateSave();
        $info = [];
        if($this->request->isPost())
        {
            $data = [
                'user_id' => $this->user->id,
                'out_id' => $this->warehouse->warehouse_id, // 借出仓库
                ] + json_decode($this->request->getContent(), true);
            foreach($data['sku'] as $k => $sku)
            {
                $info[] = [
                    'sku' => $sku,
                    'qty' => $data['qty'][$k],
                    'remark' => isset($data['t_remark']) ? $data['t_remark'][$k] : '',
                ];
            }
        }
        else
        {
            $data = $this->request->only(['borrow_id', 'status'], 'get');
        }
        WarehouseService::getInstance()->addBorrow($data, $info)
            ? $this->success('操作成功')
            : $this->error('操作失败');
    }

    /**
     * 验证借用单
     * @date 2021/02/18
     * @author longli
     */
    private function validateSave()
    {
        if($this->request->isPost())
        {
            if(!Tools::isJson($this->request->getContent(), $data)) $this->error('请求格式有误');
            $validate = \think\facade\Validate::make([
                'borrow_date'  => 'require|date',
                //'return_date'  => 'require|date',
                'sku' => 'require|array',
                'qty' => 'require|array',
            ],[
                'borrow_date.require' => '借用日期必填',
                'borrow_date.date' => '借用日期有误',
                //'return_date.require' => '退还日期必填',
                //'return_date.date' => '退还日期有误',
                'sku.require' => 'SKU 必选',
                'sku.array' => 'SKU 必须是数组',
                'qty.require' => '数量必填',
                'qty.array' => '数量必须是数组',
            ]);

            if(!$validate->batch()->check($data)) $this->error(join(', ', $validate->getError()));
            //if(strtotime($data['return_date']) < strtotime($data['borrow_date'])) $this->error('退还日期不能小于借用日期');
            foreach($data['sku'] as $k => $sku)
            {
                $qty = intval($data['qty'][$k]);
                if($qty < 1) $this->error("借用SKU【{$sku}】数量不能小于1");
                if(!WarehouseStock::isEnough($this->warehouse->warehouse_id, $sku, $qty)) $this->error("SKU【{$sku}】库存不足");
            }
        }
        else
        {
            $validate = \think\facade\Validate::make([
                'borrow_id'  => 'require',
                'status'  => 'require|number',
            ],[
                'borrow_id.require' => '非法请求',
                'status.require' => '状态必填',
                'status.number' => '状态类型错误',
            ]);
            if(!$validate->batch()->check($this->request->get()))
                $this->error(join(', ', $validate->getError()));
        }
    }
}